/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * YYYYMM 的字符串转换为 YYYY-M 格式
 * @param {string} dateStr
 * @returns
 */
export function convertToYearMonth(dateStr) {
  if (dateStr === null || dateStr === undefined || dateStr === '') {
    return ''
  }

  let year = dateStr.slice(0, 4)
  let month = parseInt(dateStr.slice(4), 10)

  // 判断月份是否在1到12之间
  if (month < 1 || month > 12) {
    return null
  }

  return `${year}-${month}`
}

/**
 * September xxxx 转换为 YYYYMM 的字符串
 * @param {string} dateStr
 * @returns
 */
export function convertToYYYYMM(dateStr) {
  if (dateStr === null || dateStr === undefined || dateStr === '') {
    return ''
  }
  let date = new Date(dateStr)
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  month = month.toString().padStart(2, '0')
  return `${year}${month}`
}

/**
 * 2024-9 转换为 YYYYMM 的字符串
 * @param {string} dateStr
 * @returns
 */
export function convertDateFormat(dateStr) {
  if (dateStr === null || dateStr === undefined || dateStr === '') {
    return ''
  }
  let [year, month] = dateStr.split('-')
  month = month.padStart(2, '0')
  return year + month
}

/**
 * 获取下一个月的最后一天
 * @returns 下一个月的最后一天
 */
export function getLastDayOfNextMonth() {
  const currentDate = new Date()
  let year = currentDate.getFullYear() // 获取当前年份和月份
  let month = currentDate.getMonth() + 1 // 下一个月 (0-11, 所以 +1)

  // 如果当前月份是12月，设置为1月，并增加年份
  if (month > 11) {
    month = 0
    year += 1
  }

  // 创建一个Date对象，设置为下下个月的1号
  const nextMonth = new Date(year, month + 1, 1)
  // 将日期设置为0，会自动调整为上个月的最后一天
  nextMonth.setDate(0)

  // 获取时分秒
  const hours = nextMonth.getHours().toString().padStart(2, '0')
  const minutes = nextMonth.getMinutes().toString().padStart(2, '0')
  const seconds = nextMonth.getSeconds().toString().padStart(2, '0')

  // 格式化日期为 YYYY-MM-DD HH:MM:SS
  const formattedDate = `${nextMonth.getFullYear()}-${(nextMonth.getMonth() + 1)
    .toString()
    .padStart(2, '0')}-${nextMonth.getDate().toString().padStart(2, '0')} ${hours}:${minutes}:${seconds}`

  return formattedDate
}

/**
 * 时间格式转换
 * @param {String} dateStr
 * @returns
 */
export function convertDate(dateStr) {
  if (dateStr === null || dateStr === undefined || dateStr === '') {
    return ''
  }
  // 如果是 YYYYMM 格式
  if (dateStr.includes('-')) {
    return dateStr
  } else {
    // 'YYYYMM' 格式，转换为 'YYYY-MM'
    let year = dateStr.slice(0, 4)
    let month = parseInt(dateStr.slice(4), 10)
    // 判断月份是否合法
    if (month < 1 || month > 12) {
      return null
    }
    return `${year}-${month}`
  }
}

/**
 * 获取当前月份的最后一天
 * @returns 当前月份的最后一天
 */
export function getLastDateOfCurrentMonth() {
  const date = new Date() // 获取当前日期
  const year = date.getFullYear() // 获取当前年份
  const month = date.getMonth() // 获取当前月份 (0 - 11)

  // 创建下个月的第一天
  const firstDayOfNextMonth = new Date(year, month + 1, 1)

  // 减去一天，得到本月的最后一天
  const lastDayOfCurrentMonth = new Date(firstDayOfNextMonth - 1)

  // 获取当前时分秒
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  const seconds = date.getSeconds().toString().padStart(2, '0')

  // 格式化为 YYYY-MM-DD HH:MM:SS
  const formattedDateTime = `${lastDayOfCurrentMonth.getFullYear()}-${(lastDayOfCurrentMonth.getMonth() + 1)
    .toString()
    .padStart(2, '0')}-${lastDayOfCurrentMonth.getDate().toString().padStart(2, '0')} ${hours}:${minutes}:${seconds}`

  return formattedDateTime
}
